<?php
/*
 * @Author: LiuHaiL 18655112670@139.com
 * @Date: 2021-12-17 11:29:08
 * @LastEditors: LiuHaiL 18655112670@139.com
 * @LastEditTime: 2022-12-05 11:17:15
 * @FilePath: \ant_form_admind:\laragon\www\ghpt_api\app\api\model\v1\AdminLog.php
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

declare(strict_types=1);

namespace app\api\model\v1;

use app\api\helpers\Auth;
use think\facade\App;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use think\facade\Request;

/**
 * @mixin \think\Model
 */
class AdminLog extends AppModel
{
    /**
     * @param string $title 标题
     * @param string $content 内容
     * @param string $uid id
     * @param string $username 昵称
     * @User: 刘海龙
     * @Date: 2021/9/22
     * @Time: 17:12
     * 日志
     */
    public static function record($title = '', $content = '', $uid = '', $username = '')
    {
        //获取url
        $url = substr(Request::url(), 0, 1500);
        //获取浏览器
        $useragent = Request::server('HTTP_USER_AGENT');
        if ($content) {
            $content = self::getPureContent($content);
        }
        $content = !is_scalar($content) ? json_encode($content, JSON_UNESCAPED_UNICODE) : $content;
        $data = [
            'title' => $title,
            'content' => $content,
            'url' => $url,
            'admin_id' => $uid,
            'username' => $username,
            'useragent' => $useragent,
            'ip' => Request::ip()
        ];
        Db::name('admin_log')->save($data);
    }

    /**
     * @param $content
     * @User: 刘海龙
     * @Date: 2021/9/22
     * @Time: 12:02
     * @return array
     * 获取已屏蔽关键信息的数据
     */
    protected static function getPureContent($content)
    {
        if (!is_array($content)) {
            return $content;
        }
        foreach ($content as $index => $item) {
            if (preg_match("/(password|token)/i", $index)) {
                $item = "***";
            } else {
                if (is_array($item)) {
                    $item = self::getPureContent($item);
                }
            }
        }
        return $content;
    }
}
